import React from 'react'
import {connect,} from 'react-redux'
import {withRouter, Link,} from 'react-router-dom'
import LocalStorageService from "../../utils/LocalStorageService";
import './topic.css'
import {Icon, Modal, NavBar, Toast} from "antd-mobile";
import TopIcon from '../../res/images/web/topic/TOP@2x.png'
import TabWithCustomUnderline from "../../layouts/TabWithCustomUnderline/TabWithCustomUnderline";
import FilterIcon from "../../res/images/web/topic/xunhuan@2x.png"
import {goBack} from "../../utils/goback";
import TopicItem from "./TopicItem/TopicItem";
import {bindEvent, getDom} from "../../utils/commonfunc";
import _ from 'lodash'
import laba from '../../res/images/web/topic/serviceWorker.png'
import SmallCoin from "../../res/images/web/shared/coin.png";
import FavoriteVote from "./FavoriteVote/FavoriteVote";
const tabHeight = 43.5
const appTabHeight = 50
const bannerHeight = 50
const gap = 8
let height = document.documentElement.clientHeight - tabHeight - appTabHeight - gap - bannerHeight

class TopicContainer extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            p: 0,
            title: '',
            txt: '', //内容
            imgs: [], //图像，二维字符串数组，{{"图片名", "图片数据"}，{"图片名", "图片数据"}...}
            fm: null,
            type: 'release',
            jinghua: 0,
            lastTop: -1,
            height: height,
        }
    }

    componentDidMount() {

        this.bindScrollEvent()

        const lastPage = this.getLastPageIndex()
        if (lastPage === -1) {
            const params = {
                type: this.state.type,
                p: 0,
            }
            this.get(params)
            this.getUser()
        } else {
            this.get({
                type: 'release',
                p: 0,
            })
            this.setState({
                p: lastPage,
            })
        }
    }


    bindScrollEvent = () => {
        const ctn = getDom('.topic-tabs > .am-tabs-pane-wrap-active')

        bindEvent(ctn, 'scroll', _.throttle(() => {
            const top = ctn.scrollTop
            const scrollHei = ctn.scrollHeight
            // const hei = this.state.height - tabHeight
            const swiperHeightToWidth = 702 / 240
            const swiperWidth = window.innerWidth - 24
            const swiperHeight = swiperWidth / swiperHeightToWidth + 24
            let ctnHei = this.props.downloadShow ? height - 60 : height
            ctnHei = ctnHei - swiperHeight
            const hei = ctnHei - tabHeight
            if (Math.abs((top + hei) - scrollHei) < 50) {
                this.setState({
                    p: this.state.p + 1
                }, () => {
                    this.get({
                        type: this.state.type,
                        p: this.state.p,
                    })
                })
            }
        }, 100))
    }

    getUser = () => {
        const uid = LocalStorageService.get('userid')
        const userDetail = this.props.user.userdetail
        const login = LocalStorageService.get('isLogin')
        const flag = userDetail.initFlag
        if (flag === 0 && login) {
            this.props.fetchUserDetail({uid,})
        }
    }

    get = (params) => {
        this.props.doFetchTopicList(params)
    }

    empty = () => {
        this.props.doEmptyTopicList()
    }

    submit = () => {
        const title = this.state.title
        const txt = this.state.txt
        const imgs = this.state.imgs
        const fm = this.state.fm
        const uid = LocalStorageService.get('userid')
        fm.append('title', title,)
        fm.append('txt', txt)
        fm.append('imgs', JSON.stringify(imgs))
        fm.append('uid', uid)
        this.props.doAddTopic(fm)
    }

    delete = (params) => {
        this.props.doDeleteTopic(params)
    }

    addTopic = () => {

        const storage = LocalStorageService
        const login = storage.get('isLogin')
        const detail = this.props.user.userdetail
        const history = this.props.history
        const {
            Gold,
            Vip,
        } = detail

        if (login === null) {
            this.props.history.push('../login')
        } else if (Vip === 0 && Gold < 10) {
            const vipPath = './vip-goods'
            const taskPath = './ren_wu'
            const alertContent = <p style={{lineHeight: '22px',}}>
                亲爱的用户，非VIP用户发帖需支付 10个<img src={SmallCoin} alt='' style={{margin: '0 4px',}}/>哦～
            </p>
            const btnList = [
                {text: '去充值', onPress: () => {history.push(vipPath)}},
                {text: <span style={{color: '#FFA500',}}>免费获取</span>, onPress: () => {history.push(taskPath)}},
            ]
            Modal.alert(alertContent, '', btnList)
        } else {
            this.props.history.push('../add-topic')
        }
    }

    onChange = (e, type) => {

        const v = e.target.value
        this.setState({
            [type]: v,
        })

    }

    getLastPageIndex = () => {
        const type = this.state.type
        const topicList = this.props.topic.topicList[type]
        const ps = Object.keys(topicList).filter(p => p !== 'end')
        if (ps.length === 0) return -1
        return Number(ps[ps.length - 1])
    }

    switchType = () => {
        const type = this.state.type
        const anotherType = type === 'comment' ? 'release' : 'comment'
        this.setState({
            type: anotherType,
        }, () => {
            const lastPage = this.getLastPageIndex()
            if (lastPage === -1) {
                this.setState({
                    p: 0,
                })
                this.get({
                    type: anotherType,
                    p: 0,
                })
            } else {
                this.listCtn.scrollIntoView()
                this.setState({
                    p: lastPage,
                })
            }
        })
        // this.empty()
    }

    onUpload = (e) => {
        const imgs = []
        const fm = new FormData()
        const fs = e.target.files
        const keys = Object.keys(fs)
        keys.map(key => {
            const file = fs[key]
            const name = file.name
            fm.append(name, file)
            imgs.push(name)
        })
        this.setState({
            imgs,
            fm,
        })
    }

    onTabClick = (tab, index) => {
        const jinghua = this.state.jinghua
        if (jinghua !== index) {
            if (index === 0) {
                // this.empty()
                this.setState({
                    jinghua: index,
                    type: 'release',
                    // p: 0,
                }, () => {
                    const lastPage = this.getLastPageIndex()
                    if (lastPage === -1) {
                        this.get({
                            p: 0,
                            type: 'release',
                        })
                    } else {
                        this.setState({
                            p: lastPage,
                        })
                    }
                })
            } else {
                // this.empty()
                this.setState({
                    // p: 0,
                    type: 'jinghua',
                    jinghua: index,
                }, () => {
                    const lastPage = this.getLastPageIndex()
                    if (lastPage === -1) {
                        this.get({
                            p: 0,
                            // type
                            type: 'jinghua'
                        })
                    } else {
                        this.setState({
                            p: lastPage,
                        })
                    }

                })
            }
        }
    }

    onTouchEnd = e => {

        const ctn = this.listCtn
        const last = ctn.lastElementChild
        const rect = last.getBoundingClientRect()
        const cH = document.documentElement.clientHeight
        const top = rect.top
        const end = this.props.topic.end

        if (cH > top  && !end) {
            this.setState({
                p: this.state.p + 1
            }, () => {
                this.get({
                    type: this.state.type,
                    p: this.state.p,
                })
            })
        }
    }

    render() {

        const download = this.props.downloadShow
        const history = this.props.history
        const topicList = this.props.topic.topicList
        const type = this.state.type
        const end = topicList[type].end
        let list = []
        if (topicList !== {}) {
            const ps = Object.keys(topicList[type]).filter(key => key !== 'end')
            ps.map(p => list.push(...topicList[type][p]))
        }

        const jinghua = this.state.jinghua

        const typeM = {
            'release': '最新发布',
            'comment': '最新回复',
        }

        const leftContent = <Icon
            type="left"
            size='lg'
            style={{color: `black`}}
            onClick={() => goBack(history)}
        />

        const head = <div className='topic-ctn-head'>
            <NavBar
                leftContent={leftContent}
                style={{
                    background: 'transparent',
                }}
            >
                #足球# 话题讨论区
            </NavBar>
            <p className='topic-ctn-head-desc'>
                关于足球你有什么猛料或者想法吗？ 欢迎在这里和大家一起讨论哦！
            </p>

        </div>

        const top = <div className='topic-top'>
            <div className='topic-top-item flex-center-align-center'>
                <img src={TopIcon} alt='' style={{width: 21, height: 29, marginRight: 8}}/>
                <div style={{
                    position: 'relative',
                    background: '#F3F3F3',
                    height: '34px',
                    borderRadius: '4px',
                    width: '85%',
                }}>
                    <p style={{
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        width: '100%',
                        textAlign: 'center',
                        transform: 'translate(-50%, -50%)',
                    }}>（以免封禁，请阅读规范）外围和社交封号处理</p>
                </div>
            </div>
        </div>

        const banner = <div
            style={{
                width: '100%',
                background: '#fff',
                marginBottom: gap,
                height: bannerHeight,
                padding: '8px',
            }}
        >
            <div
                className='flex-align-center'
                style={{
                    background: '#F3F3F3',
                    width: '100%',
                    height: '34px',
                    padding: '8px',
                }}
            >
                <img src={laba} style={{width: 16, height: 16, marginRight: '8px',}} />
                <p>(以免封禁，请<Link to='./topic-rules'><span style={{textDecoration: 'underline'}}>阅读规范</span></Link>)外围和社交封号处理！</p>

            </div>

        </div>


        const tabs = [
            {title: '全部',},
            {title: '精选',},
        ]

        const listTemplate = list.map((topic, index) => <TopicItem key={index} topic={topic} history={history}/>)

        const typeText = typeM[type]
        const switchIcon = <div
            className='topic-filter flex-center-align-center'
            onClick={this.switchType}
        >
            <span>{typeText}</span>
            <img src={FilterIcon} alt='' style={{height: 12, width: 12,}}/>
        </div>

        const scrollList = <div
            className='topic-list-ctn'
            // onTouchEnd={e => this.onTouchEnd(e)}
            ref={el => this.listCtn = el}
        >
            {listTemplate}
        </div>

        const swiperHeightToWidth = 702 / 240
        const swiperWidth = window.innerWidth - 24
        const swiperHeight = swiperWidth / swiperHeightToWidth + 24
        let height = this.state.height
        height = height - swiperHeight
        const main = <div
            style={{
                position: 'relative',
            }}
        >

            {jinghua === 1 ? null : switchIcon}

            <div
                className='add-topic'
                onClick={this.addTopic}
            >
                <span>发帖</span>
            </div>

            <div style={{height: download ? height - 60 : height,}}>
                <TabWithCustomUnderline
                    tabs={tabs}
                    prefixCls='topic-tabs'
                    animated={false}
                    onTabClick={(tab, index) => this.onTabClick(tab, index)}
                    tabBarUnderlineStyle={{
                        border: '2px solid #36C8B9',
                    }}
                >
                    {scrollList}
                </TabWithCustomUnderline>
            </div>

        </div>

        return <div
            className='fixed-full-container'
            style={{
                // top: '43.5px',
                top: download ? '103.5px' : '43.5px',
            }}
        >
            {/*{head}*/}
            {/*{top}*/}
            <FavoriteVote />
            {banner}
            {main}
        </div>
    }

}



const mapState = (state) => ({
    user: state.user,
    topic: state.topic,
})

const mapDispatch = (dispatch) => ({
    doAddTopic: (payload) => dispatch.topic.doAddTopic(payload),
    doDeleteTopic: (payload) => dispatch.topic.doDeleteTopic(payload),
    doFetchTopicList: (payload) => dispatch.topic.doFetchTopicList(payload),
    doEmptyTopicList: () => dispatch.topic.doEmptyTopicList(),
    fetchUserDetail: (payload) => dispatch.user.fetchUserDetail(payload)
})

export default connect(mapState, mapDispatch)(withRouter(TopicContainer))
